package com.zhangfb95.crosschain.server.infra.config.configuration;

import com.zhangfb95.crosschain.infra.model.Result;
import com.zhangfb95.crosschain.infra.statuscode.StatusCode;
import com.zhangfb95.crosschain.infra.util.json.JsonUtil;
import com.zhangfb95.crosschain.server.infra.config.properties.WebServerProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @author zhangfubing
 * @since 2023/10/18
 */
@Slf4j
@Component
public class CheckWebHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private WebServerProperties webServerProperties;
    @Autowired
    private JsonUtil jsonUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestURI = request.getRequestURI();
        int localPort = request.getLocalPort();

        String allowedUriPrefix = null;
        for (WebServerProperties.Host host : webServerProperties.getHosts()) {
            if (Objects.equals(localPort, host.getPort())) {
                allowedUriPrefix = host.getUriPrefix();
                if (requestURI.startsWith(host.getUriPrefix())) {
                    return HandlerInterceptor.super.preHandle(request, response, handler);
                }
            }
        }

        log.info("not find, localPort: {}, allowedUriPrefix: {}, requestURI: {}",
                localPort, allowedUriPrefix, requestURI);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        String body = jsonUtil.toJsonQuietly(Result.fail(StatusCode.NOT_FOUND.getCode(), "Not Found"));
        response.getWriter().write(body);
        response.getWriter().flush();
        return false;
    }
}
